from rest_framework import viewsets, permissions, status, filters, serializers
from rest_framework.decorators import action
from rest_framework.response import Response
# 暂时注释掉 django_filters 依赖
# from django_filters.rest_framework import DjangoFilterBackend
from .models import Prompt, Tag, AIModel, PromptVersion
from .serializers import (
    PromptListSerializer, PromptDetailSerializer, TagSerializer,
    AIModelSerializer, PromptCreateUpdateSerializer, PromptVersionSerializer
)
from .permissions import IsOwnerOrReadOnly


class TagViewSet(viewsets.ModelViewSet):
    """标签视图集"""
    serializer_class = TagSerializer
    permission_classes = [permissions.IsAuthenticated]
    filter_backends = [filters.SearchFilter]
    search_fields = ['name']

    def get_queryset(self):
        return Tag.objects.filter(user=self.request.user)

    def perform_create(self, serializer):
        serializer.save(user=self.request.user)


class AIModelViewSet(viewsets.ReadOnlyModelViewSet):
    """AI模型视图集"""
    queryset = AIModel.objects.filter(is_active=True)
    serializer_class = AIModelSerializer
    permission_classes = [permissions.IsAuthenticated]


class PromptViewSet(viewsets.ModelViewSet):
    """提示词视图集"""
    permission_classes = [IsOwnerOrReadOnly]
    filter_backends = [filters.SearchFilter, filters.OrderingFilter]
    filterset_fields = ['tags', 'ai_model']
    search_fields = ['title', 'description', 'content']
    ordering_fields = ['created_at', 'updated_at', 'title', 'likes_count', 'views_count']
    ordering = ['-updated_at']

    def get_serializer_class(self):
        if self.action == 'list':
            return PromptListSerializer
        elif self.action in ['create', 'update', 'partial_update']:
            return PromptCreateUpdateSerializer
        return PromptDetailSerializer

    def get_queryset(self):
        user = self.request.user
        # 如果是列表视图，可以查看公开的提示词
        if self.action == 'list':
            if user.is_authenticated:
                return Prompt.objects.filter(user=user) | Prompt.objects.filter(is_public=True)
            else:
                return Prompt.objects.filter(is_public=True)
        # 其他情况只能查看自己的提示词
        if user.is_authenticated:
            return Prompt.objects.filter(user=user)
        else:
            return Prompt.objects.none()

    def perform_create(self, serializer):
        # 检查用户是否达到提示词限制
        user = self.request.user
        if user.prompt_count >= user.prompt_limit:
            raise serializers.ValidationError({"detail": "您已达到提示词数量上限，请升级会员以获取更多配额"})
        
        # 保存提示词并更新用户的提示词计数
        prompt = serializer.save(user=user)
        user.prompt_count += 1
        user.save(update_fields=['prompt_count'])
        return prompt

    @action(detail=True, methods=['post'])
    def copy(self, request, pk=None):
        """复制提示词"""
        prompt = self.get_object()
        
        # 检查用户是否达到提示词限制
        user = request.user
        if user.prompt_count >= user.prompt_limit:
            return Response(
                {"detail": "您已达到提示词数量上限，请升级会员以获取更多配额"},
                status=status.HTTP_400_BAD_REQUEST
            )
        
        # 创建新的提示词
        new_prompt = Prompt.objects.create(
            user=user,
            title=f"{prompt.title} (复制)",
            description=prompt.description,
            content=prompt.content,
            ai_model=prompt.ai_model,
            is_public=False  # 默认设为私有
        )
        
        # 复制标签
        new_prompt.tags.set(prompt.tags.all())
        
        # 创建第一个版本
        PromptVersion.objects.create(
            prompt=new_prompt,
            content=prompt.content,
            version_number=1
        )
        
        # 更新用户的提示词计数
        user.prompt_count += 1
        user.save(update_fields=['prompt_count'])
        
        return Response(
            PromptDetailSerializer(new_prompt).data,
            status=status.HTTP_201_CREATED
        )

    @action(detail=False, methods=['get'])
    def stats(self, request):
        """获取提示词统计信息"""
        user = request.user
        total_prompts = Prompt.objects.filter(user=user).count()
        prompt_limit = user.prompt_limit
        remaining = max(0, prompt_limit - user.prompt_count)
        
        return Response({
            'total': total_prompts,
            'limit': prompt_limit,
            'used': user.prompt_count,
            'remaining': remaining
        })

    @action(detail=False, methods=['post'])
    def batch_delete(self, request):
        """批量删除提示词"""
        prompt_ids = request.data.get('ids', [])
        if not prompt_ids:
            return Response({"detail": "未提供要删除的提示词ID"}, status=status.HTTP_400_BAD_REQUEST)
        
        # 只删除用户自己的提示词
        deleted_count = Prompt.objects.filter(id__in=prompt_ids, user=request.user).delete()[0]
        
        # 更新用户的提示词计数
        user = request.user
        user.prompt_count = Prompt.objects.filter(user=user).count()
        user.save(update_fields=['prompt_count'])
        
        return Response({"detail": f"成功删除{deleted_count}个提示词"})
